package org.noisyteam.fxplaylistgrabber.service;

import net.moraleboost.streamscraper.ScrapeException;
import net.moraleboost.streamscraper.Scraper;
import net.moraleboost.streamscraper.Stream;
import net.moraleboost.streamscraper.scraper.IceCastScraper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import sun.beans.editors.StringEditor;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

@Service
public class PlaylistProviderService {
    private static final Logger logger = LoggerFactory.getLogger(PlaylistProviderService.class);

    private static final String MEDIASTREAM = "http://online-radioroks.tavrmedia.ua/RadioROKS";
    private static final String MSTREAM = "http://46.182.85.199:8000/kiss";

    private static List<String> playlist = new LinkedList<String>();

    @Scheduled(fixedDelay = 30000)
    public void refresh() {
        logger.debug("Scheduled task firing");
        try {
            Scraper scraper = new IceCastScraper();
            List<Stream> streams = scraper.scrape(new URI(MEDIASTREAM));
            for (Stream stream : streams) {
                if (stream.getUri().toString().equals(MEDIASTREAM)) {
                    String currentSong = new String(stream.getCurrentSong().getBytes(Charset.forName("ISO-8859-1")), "UTF-8");
                    if (playlist.size() > 0) {
                        if (!currentSong.equals(playlist.get(0))) {
                            playlist.add(0, currentSong);
                        }
                    } else {
                        playlist.add(0, currentSong);
                    }
                    if (playlist.size() > 10) {
                        playlist.remove(playlist.size()-1);
                    }
                }
            }
        } catch (ScrapeException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (URISyntaxException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public List<String> getPlaylist() {
        return playlist;
    }

    public static void main(String[] args) {
        new PlaylistProviderService().refresh();
    }
}
